package com.shanghaionstar.nav.presenter;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.support.v4.app.FragmentManager;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.sqlite.entities.PoiSearchHistory;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.map.common.PoiType;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.adapter.NavPoiSearchHistoryAdapter;
import com.shanghaionstar.nav.iview.INavSetAddressView;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.model.SetAddressResult;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.utils.NavHolder;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Action1;

/**
 * Created by 6335yz on 2016/7/18.
 */
public class NavSetAddressPresenter extends BasePresenter implements MapHandler.OnMapSearchCallBack {

    private AbstractMapActivity mapActivity;
    private Resources res;
    private INavSetAddressView navSetAddressView;
    private MapHandler mapHandler;

    private List<PoiItemInfo> searchPoiList = new ArrayList<>();
    private FragmentManager fragmentManager;
    private NavService navService;

    private List<PoiSearchHistory> searchHistoryDataLists = new ArrayList<PoiSearchHistory>();
    private SearchHistoryImpl searchHistoryImpl;
    private NavPoiSearchHistoryAdapter historyAdapter;
    private SearchHistoryImpl searchHistory;
    //搜索历史
    private List<PoiSearchHistory> searchHistoryList;
    private UserAddressInfoImpl userAddressInfoImpl;

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        navSetAddressView = (INavSetAddressView) view;
    }

    public NavSetAddressPresenter(IMVPScheduler mvpScheduler, AbstractMapActivity mapActivity, MapHandler mapHandler) {
        super(mvpScheduler);
        this.mapActivity = mapActivity;
        this.mapHandler = mapHandler;
        res = this.mapActivity.getResources();
        this.mapHandler.registOnMapSearchCallBack(this);
        fragmentManager = mapActivity.getSupportFragmentManager();
        navService = new NavService(mapActivity);
        searchHistory = new SearchHistoryImpl(mapActivity);
        userAddressInfoImpl = new UserAddressInfoImpl(mapActivity);

    }

    public void getSearchHistroy() {
        searchHistoryList = searchHistory.getSearchList();
        if (searchHistoryList != null && searchHistoryList.size() > 0) {
            if (navSetAddressView != null) {
                navSetAddressView.showCleanBtnOrNot(true);
                navSetAddressView.showSearchHistory(searchHistoryList);
            }
        } else {
            if (navSetAddressView != null) {
                navSetAddressView.showCleanBtnOrNot(false);
            }
        }
    }


    @Override
    public void onSearchSuccess(List<PoiItemInfo> results, int pageIndex, int totalPages) {
        if (navSetAddressView != null) {
            navSetAddressView.showMapLoading(false, "");
            searchPoiList.addAll(results);
            if (results != null && results.size() > 0) {
                navSetAddressView.showSearchResult(searchPoiList);
            } else {
                navSetAddressView.showSearchResultWithNodata();
            }
        }
    }

    @Override
    public void onSearchFail(LocationType locationType) {

    }

    public void search(String searchName) {
        mapActivity.hideSoftInput();
        if (CommonUtil.isNull(searchName)) {
            if (navSetAddressView != null) {
                navSetAddressView.onResponseError(new OnStarException("", mapActivity.getString(R.string.poi_not_search_not_condition)));
            }
        } else {
            searchName = searchName.trim();
            if (navSetAddressView != null) {
                navSetAddressView.showCleanBtnOrNot(false);
                navSetAddressView.showMapLoading(true, mapActivity.getString(R.string.poi_searching));
                mapHandler.searchByName(searchName, PoiType.All.getStringValue(), NavHolder.getInstance(mapActivity).getCurrentCity());
            }
        }
    }

    public void clearHistory() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity, android.app.AlertDialog.THEME_HOLO_LIGHT);
        builder.setMessage(res.getString(R.string.poi_need_clear));
        builder.setPositiveButton(res.getString(R.string.submit), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (searchHistoryList != null && searchHistoryList.size() > 0) {
                    searchHistory.deleteAll();
                    searchHistoryList.clear();
                    if (navSetAddressView != null) {
                        navSetAddressView.showCleanBtnOrNot(false);
                        navSetAddressView.showSearchHistory(searchHistoryList);
                    }
                }
            }
        });
        builder.setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(true);
        builder.show();
    }


    public void submit(final PoiItemInfo poiItemInfo, final MapChoosePoiType mapChoosePoiType) {
//        if (CommonUtil.isNull(poiName) && CommonUtil.isNull(poiAddress)) {
//            if(navSetAddressView!=null) {
//                navSetAddressView.onResponseError(new OnStarException("",res.getString(R.string.nav_no_map_point)));
//            }
//        } else {
        // 点击确定返回到设置回家地址页面
        if (mapChoosePoiType == MapChoosePoiType.HOME || mapChoosePoiType == MapChoosePoiType.COMPANY) {
            subscription = navService.dosaveHomeOrCompanyAddressInfo(poiItemInfo, mapChoosePoiType)
                    .subscribeOn(mvpScheduler.backgroundThread())
                    .observeOn(mvpScheduler.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String s) {
                            if (mapChoosePoiType == MapChoosePoiType.HOME) {
                                userAddressInfoImpl.saveUserAddressInfo(poiItemInfo, "1");
                            } else if (mapChoosePoiType == MapChoosePoiType.COMPANY) {
                                userAddressInfoImpl.saveUserAddressInfo(poiItemInfo, "2");
                            }
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            //里面抛出的Error信息
                            if (navSetAddressView != null) {
                                navSetAddressView.onResponseError((OnStarException) throwable);
                            }
                        }
                    });
        }
//        if (navSetAddressView != null) {
//            if (mapChoosePoiType == MapChoosePoiType.HOME) {
//                mapActivity.getNavDataHolder().setMapHomeChoosePoi(poiItemInfo);
//                navSetAddressView.onReponseSuccess(poiItemInfo);
//            } else if (mapChoosePoiType == MapChoosePoiType.COMPANY) {
//                mapActivity.getNavDataHolder().setMapCompChoosePoi(poiItemInfo);
//                navSetAddressView.onReponseSuccess(poiItemInfo);
//            } else if (mapChoosePoiType == MapChoosePoiType.START_POI) {
//                mapActivity.getNavDataHolder().setStartPoi(poiItemInfo);
//            } else if (mapChoosePoiType == MapChoosePoiType.END_POI) {
//                mapActivity.getNavDataHolder().setEndPoi(poiItemInfo);
//            }
//            navSetAddressView.onReponseSuccess(poiItemInfo);
//        }
        Intent intent = new Intent();
        SetAddressResult setAddressResult = new SetAddressResult();
        setAddressResult.mapChoosePoiType = mapChoosePoiType;
        setAddressResult.poiItemInfo = poiItemInfo;
        intent.putExtra("result",setAddressResult);
        mapActivity.setResult(1,intent);
        mapActivity.finish();
//        }
    }

}
